<template>
    <div class="edit-container">
        <nut-popup :visible="props.visible" position="bottom" @update:visible="(val:boolean) => emits('update:visible', val)" @closed="closed">
            <div class="header">分组编辑</div>
            <nut-form ref="formRef" :rules="rules" :model-value="state.form">
                <nut-form-item label="名称" prop="groupName">
                    <nut-input v-model="state.form.groupName" placeholder="请输入名称" type="text" />
                </nut-form-item>
            </nut-form>
            <div class="footer">
                <nut-button class="cancel" type="default" @click="emits('update:visible', false)">取消</nut-button>
                <nut-button class="save" type="info" @click="save">保存</nut-button>
            </div>
        </nut-popup>
        <Notify ref="notifyRef" />
    </div>
</template>

<script lang="ts">
export default { name: '' }
</script>

<script lang="ts" setup>
import { reactive, ref, nextTick, onMounted, useAttrs, useSlots } from 'vue'
import Notify from '@/components/system/Notify.vue'
import { Form } from '@nutui/nutui-taro'
import { $http } from '@/request'

const formRef = ref<InstanceType<typeof Form>>()
const notifyRef = ref<InstanceType<typeof Notify>>()



const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    }
})

const rules = {
    groupName: [
        { required: true, message: '请输入名称' }
    ]
}
const state = reactive({
    form: {
        groupId: -1,
        groupName: ''
    }
})

const emits = defineEmits<{
    (e: 'update:visible', value: boolean): void
    (e: 'refresh', value: typeof state.form): void
}>()

const save = () => {
    formRef.value?.validate().then(({ valid }) => {
        if (!valid) return
        const operate = state.form.groupId === -1 ? '添加' : '修改'
        $http.updateGroup(state.form).then(r => {
            notifyRef.value?.$success(`${operate}成功`)
            emits('update:visible', false)
            emits('refresh', { ...state.form })
        }).catch(e => {
            notifyRef.value?.$error(e.data?.message ?? `${operate}失败`)
        })
    }).catch(e => { })
}

const closed = () => {
    state.form.groupId = -1
    state.form.groupName = ''
}

const setCurrent = (groupId = -1, groupName: string) => {
    state.form.groupId = groupId
    state.form.groupName = groupName
}
defineExpose({
    setCurrent
})
</script>
<style lang="scss" scoped>
.edit-container {
    .header {
        margin-top: 16px;
        text-align: center;
        color: gray;
    }
    .nut-form {
        .value-input {
            margin-bottom: 20px;
        }
    }
    .footer {
        display: flex;
        .nut-button {
            margin: 10px;
            &.cancel {
                flex: 3;
            }
            &.save {
                flex: 7;
            }
        }
    }
}
</style>